package me.xiaoyan.android.net;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import me.xiaoyan.android.widget.BaseUtil;
import me.xiaoyan.android.widget.YLog;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;

/**
 * 
 * @author xiaoyan
 * 
 */
public class AsyncImageLoader {
	private static final String TAG = YLog.getTag(AsyncImageLoader.class);
	public Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
	private ExecutorService executorService = Executors.newFixedThreadPool(5); // 固定五个线程来执行任务
	private final Handler handler = new Handler();

	/**
	 * 异步获取图片
	 * 
	 * @param imageUrl
	 * @param callback
	 */
	public void getBitMap(final String imageUrl, final ImageCallback callback) {
		Bitmap cache = BaseUtil.getImageCache(imageUrl);
		if (null != cache) {
			callback.imageLoaded(cache);
		} else {
			// 缓存中没有图像，则从网络上取出数据，并将取出的数据缓存到内存中
			executorService.submit(new Runnable() {
				@Override
				public void run() {
					try {
						final Bitmap bitmap = loadImageFromUrl(imageUrl);
						handler.post(new Runnable() {
							@Override
							public void run() {
								callback.imageLoaded(bitmap);
							}
						});
						BaseUtil.saveImageCache(imageUrl, bitmap);
					} catch (Exception e) {
						YLog.e(TAG, "Exception(59)",e.toString());
					}
				}
			});
		}
	}

	/**
	 * 同步获取网络图片数据 返回bitmap
	 * 
	 * @param imageUrl
	 * @return
	 */
	public Bitmap loadImageFromUrl(String imageUrl) {
		YLog.d(TAG, "loadImageFromUrl", imageUrl);
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				return softReference.get();
			}
		}
		try {
			HttpGet hg = new HttpGet(imageUrl);
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(hg);

			HttpEntity entity = response.getEntity();
			BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
					entity);
			InputStream is = bufferedHttpEntity.getContent();
			BitmapFactory.Options op = new BitmapFactory.Options();
			op.inJustDecodeBounds = true;
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			is.close();
			imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
			return bitmap;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public interface ImageCallback {
		// the first time callback
		public void imageLoaded(Bitmap drawable);
	}
}
